<template>
  <div>
    <a-dropdown v-if="currentUser && currentUser.name" placement="bottomRight">
      <span class="ant-pro-account-avatar">
        <a-avatar size="small" :src="getImageUrl()" class="antd-pro-global-header-index-avatar" />
        <span>{{ currentUser.name }}</span>
      </span>
      <template v-slot:overlay>
        <a-menu class="ant-pro-drop-down menu" :selected-keys="[]">
          <!-- <a-menu-item v-if="menu" key="center" @click="handleToCenter">
            <a-icon type="user" />
            {{ $t('menu.account.center') }}
          </a-menu-item> -->
          <a-menu-item v-if="menu" key="settings" @click="handleToSettings">
            <a-icon type="setting" />
            {{ $t('menu.account.settings') }}
          </a-menu-item>
          <a-menu-item v-if="menu" key="password" @click="clickEditPassword">
            <a-icon type="setting" />
            {{ '修改密码' }}
          </a-menu-item>
          <a-menu-divider v-if="menu" />
          <a-menu-item key="logout" @click="handleLogout">
            <a-icon type="logout" />
            {{ $t('menu.account.logout') }}
          </a-menu-item>
        </a-menu>
      </template>
    </a-dropdown>
    <span v-else>
      <a-spin size="small" :style="{ marginLeft: 8, marginRight: 8 }" />
    </span>
    <a-modal title="修改密码" :visible="modalVisible" width="600px" @ok="handleOk" @cancel="handleCancel">
      <a-form-model
        :model="form"
        :rules="formRules"
        ref="formRef"
        :label-col="labelCol"
        :wrapper-col="wrapperCol">
        <a-form-model-item label="请输入新密码" prop="pwd">
          <a-input-password v-model="form.pwd" :maxLength="30" placeholder="至少8位包含数字、大小写英文、特殊符号(“!@#$%^&*.?”)" />
        </a-form-model-item>
        <a-form-model-item label="确认新密码" prop="pwdConfirm">
          <a-input-password v-model="form.pwdConfirm" :maxLength="30" placeholder="至少8位包含数字、大小写英文、特殊符号(“!@#$%^&*.?”)" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import monitor from '@/utils/monitor'
import avatarDropdown from '@/monitor/globalHeader/avatarDropdown.js'

import { updatePassword } from '@/api/system/user'
import { Modal } from 'ant-design-vue'

const watch = monitor(avatarDropdown)

export default {
  name: 'AvatarDropdown',
  props: {
    currentUser: {
      type: Object,
      default: () => null
    },
    menu: {
      type: Boolean,
      default: true
    }
  },
  data () {
    const validatorConfirmPwd = (rule, value, callback) => {
      if (this.form.pwd === this.form.pwdConfirm) {
        callback()
      } else {
        callback(new Error('两次密码不一致！'))
      }
    }
    return {
      modalVisible: false,
      form: {
        pwd: '',
        pwdConfirm: ''
      },
      labelCol: { span: 5 },
      wrapperCol: { span: 18 },
      formRules: {
        pwd: [
          { required: true, message: '请输入密码', trigger: 'change' },
          { pattern: /^\S*(?=\S{8,})(?=\S*\d)(?=\S*[A-Z])(?=\S*[a-z])(?=\S*[!@#$%^&*.? ])\S*$/, message: '至少8位包含数字、大小写英文、特殊符号(包含“!@#$%^&*.?”)' }
          // { pattern: /^[^\u4e00-\u9fa5]{8,}$/, message: '至少为8位包含数字、英文字母、特殊符号组合' }
        ],
        pwdConfirm: [
          { required: true, message: '请输入确认新密码', trigger: 'change' },
          { pattern: /^\S*(?=\S{8,})(?=\S*\d)(?=\S*[A-Z])(?=\S*[a-z])(?=\S*[!@#$%^&*.? ])\S*$/, message: '至少8位包含数字、大小写英文、特殊符号(“!@#$%^&*.?”)' },
          { required: true, trigger: 'blur', validator: validatorConfirmPwd }
        ]
      }
    }
  },
  methods: watch({
    getImageUrl () {
      if (this.currentUser.headimg) {
        return this.$options.filters.dealImageUrl(this.currentUser.headimg)
      } else {
        return 'https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png'
      }
    },
    handleToCenter () {
      this.$router.push({ path: '/account/center' })
    },
    handleToSettings () {
      this.$router.push({ path: '/settings' })
    },
    // 点击修改密码
    clickEditPassword () {
      this.modalVisible = true
    },
    handleOk () {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          this.updatePassword()
        }
      })
    },
    updatePassword () {
      updatePassword({ pwd: this.form.pwd })
        .then(res => {
          this.$message.success('密码修改成功')
          this.handleCancel()
          this.changePassword()
          // 修改密码成功 退出登录
          this.$store.dispatch('Logout').then(() => {
            this.$router.push({ name: 'login' })
          })
        })
        .catch(() => {})
    },
    // 点击取消关闭对话框并重置
    handleCancel () {
      this.modalVisible = false
      setTimeout(() => {
        this.$refs.formRef.resetFields()
      }, 200)
    },
    handleLogout (e) {
      Modal.confirm({
        title: this.$t('layouts.usermenu.dialog.title'),
        content: this.$t('layouts.usermenu.dialog.content'),
        okText: '确定',
        cancelText: '取消',
        onOk: () => {
          this.$emit('logout', 1)
          // return new Promise((resolve, reject) => {
          //   setTimeout(Math.random() > 0.5 ? resolve : reject, 1500)
          // }).catch(() => console.log('Oops errors!'))
          return this.$store.dispatch('Logout', 1).then(() => {
            this.$router.push({ name: 'login' })
          })
        },
        onCancel () {}
      })
    },
    // 修改密码埋点
    changePassword () {}
  })
}
</script>

<style lang="less" scoped>
.ant-pro-drop-down {
  /deep/ .action {
    margin-right: 8px;
  }
  /deep/ .ant-dropdown-menu-item {
    min-width: 160px;
  }
}
</style>
